package com.lk.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/*
    Post 方式  不管tomcat什么版本都有乱码问题
    Get  方式  tomcat 7及以下会乱码
    以上不会乱码

 */
@WebFilter("/*")//过滤所有资源
public class EncodingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        //处理Post请求有效，Get请求不受影响
        request.setCharacterEncoding("utf-8");
        //得到请求类型
        String method =request.getMethod();

        if("Get".equalsIgnoreCase(method)){//忽略大小写
            String serviceInfo = request.getServletContext().getServerInfo();//服务器版本信息 Apache Tomcat/7.0.1
            //截取字符串获取版本
            String version=serviceInfo.substring(serviceInfo.lastIndexOf("/")+1,serviceInfo.indexOf("."));
            if(version!=null&&Integer.parseInt(version)<8){
                //get方式的tomcat7以下版本
                MyWapper myRequest=new MyWapper(request);
                filterChain.doFilter(myRequest,response);
                return;
            }
        }
        filterChain.doFilter(request,response);

    }
    //定义内部类，本质是一个request对象
    //重写getParameter方法，在其中对编码进行转换
    class MyWapper extends HttpServletRequestWrapper{

        //定义成员变量提升构造器中request的作用域
        private HttpServletRequest request;

        public MyWapper(HttpServletRequest request) {
            super(request);
            this.request=request;
        }

        @Override
        public String getParameter(String name) {
            //获取乱码的参数
            String value=super.getParameter(name);
            if(value==null){
                return value;
            }
            try {
                value=new String(value.getBytes("ISO-8859-1"),"UTF-8");
            }catch (Exception e){
                e.printStackTrace();
            }
            return value;
        }

    }
}
